package com.fzd.code.account.web;

import com.fzd.code.account.orm.model.Account;
import com.fzd.code.account.service.IAuthService;
import com.fzd.code.account.service.ICaptchaService;
import com.fzd.code.auth.token.Authorization;
import com.fzd.code.auth.token.TokenManager;
import com.fzd.code.common.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;

/**
 * 获取和删除token的请求地址，在Restful设计中其实就对应着登录和退出登录的资源映射
 * @author ScienJus
 * @date 2015/7/30.
 */
@RestController
@RequestMapping("/tokens")
public class TokenController {

    @Autowired
    private TokenManager tokenManager;
    @Autowired
    private ICaptchaService captchaService;
    @Qualifier("common-auth-service")
    @Autowired
    private IAuthService commonAuthService;
    @Qualifier("common-ldap-service")
    @Autowired
    private IAuthService ldapAuthService;

    @PostMapping
    public Result login(Account account, HttpServletRequest request) throws Exception{
        Result.failedThrow(
                this.captchaService.valid(account.getCaptchaId(),account.getCaptcha()),
                "验证码错误"
        );

        Account loggedAccount = null;
        if(account.getLoginMethod().equals("common")){
            loggedAccount = commonAuthService.login(account);
        }
        if(account.getLoginMethod().equals("ldap")){
            loggedAccount = ldapAuthService.login(account);
        }

        if(loggedAccount == null) throw new Exception("用户名或密码错误");

        String token = tokenManager.createToken(account.getAccountId());
        return Result.OK(new HashMap<String,Object>())
                .data("userId",account.getAccountId())
                .data("token",token);
    }

    @DeleteMapping("/{accountId}")
    @Authorization
    public boolean logout(@PathVariable String accountId) throws Exception{
        return tokenManager.deleteToken(accountId);
    }

}
